package com.bingxue.edu.framework.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author panbo
 * @since 2024/6/28
 */
@Component
@SuppressWarnings("unchecked")
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> typeName) {
        return context.getBean(typeName);
    }

    public static List<Object> getBeanListByAnnotation(Class<? extends Annotation> annotationType) {
        Map<String, Object> map = context.getBeansWithAnnotation(annotationType);
        return new ArrayList<>(map.values());
    }



    public static void publishEvent(Object event) {
        context.publishEvent(event);
    }

}
